package itdep.jsf.internal;

import javax.el.ELContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Ivan Khalopik
 * @version $Revision: 23 $ $Date: 2010-06-19 09:36:09 +0000 (Sat, 19 Jun 2010) $
 */
public class SelectModelUtils {
	private static final List<SelectItem> EMPTY_MODEL = Collections.emptyList();

	public static List<SelectItem> buildEmpty() {
		return EMPTY_MODEL;
	}

	public static <V> List<SelectItem> buildSimple(List<V> values) {
		final List<SelectItem> selectItems = new ArrayList<SelectItem>();
		for (V value : values) {
			selectItems.add(new SelectItem(value));
		}
		return selectItems;
	}

	public static <V> List<SelectItem> buildFormatted(List<V> values, String format, String... parameters) {
		final ELContext context = FacesContext.getCurrentInstance().getELContext();
		final List<SelectItem> selectItems = new ArrayList<SelectItem>();
		for (V value : values) {
			selectItems.add(new SelectItem(value, getLabel(context, value, format, parameters)));
		}
		return selectItems;
	}

	private static String getLabel(ELContext context, Object value, String format, String... parameters) {
		if (value == null) return "";
		final List<Object> args = new ArrayList<Object>();
		for (String parameter : parameters) {
			args.add(context.getELResolver().getValue(context, value, parameter));
		}
		return String.format(format, args.toArray());
	}

}
